﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using SimpleWebApi.Model.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleWebApi.EFCore.Context
{
    public class BaseDbContext:DbContext
    {

        public DbSet<UserEntity> User { get; set; }


        public BaseDbContext(DbContextOptions<BaseDbContext> options)
           : base(options)
        {
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.UseCollation("utf8mb4_unicode_ci");

            //表名添加前缀
            foreach (IMutableEntityType entity in modelBuilder.Model.GetEntityTypes())
                entity.SetTableName($"Api_{entity.GetTableName()}");

            // 全局配置所有 DateTime 属性为精度 0（秒）
            foreach (var property in modelBuilder.Model.GetEntityTypes()
                .SelectMany(t => t.GetProperties())
                .Where(p => p.ClrType == typeof(DateTime) || p.ClrType == typeof(DateTime?)))
            {
                property.SetColumnType("datetime(0)"); // MySQL
                                                       //property.SetColumnType("datetime2(0)"); // SQL Server
            }

            //用户名唯一
            modelBuilder.Entity<UserEntity>()
                 .HasIndex(u => u.UserName)
                 .IsUnique();


        }
    }
}
